<template>
  <div class="app-container">
    <div class="container-bg">
      <div class="filter-container">
        <el-date-picker
          style="width: 380px"
          class="filter-item m-margin-l10"
          v-model="dateTime"
          type="datetimerange"
          range-separator="~"
          value-format="yyyy-MM-dd HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          :default-time="['00:00:00', '23:59:59']"
        >
        </el-date-picker>
        <el-button
          class="filter-item m-margin-l10"
          type="primary"
          icon="el-icon-search"
          @click="onSearch"
          >查询
        </el-button>
        <el-button
          class="filter-item m-margin-l10"
          type="warning"
          icon="el-icon-refresh"
          @click="onReset"
          >重置
        </el-button>
        <div style="float: right; display: flex" v-if="isAdmin">
          <el-button type="success" @click="doDownloadFile" :disabled="personData.list &&personData.list.length == 0"
            v-if="false"
          >导出 </el-button>
          <el-button type="danger" icon="el-icon-delete" @click="handleDeleteBatch" plain v-if="false"
            >批量删除</el-button
          >
          <el-button type="danger" icon="el-icon-delete" @click="delDoorRecordsAll"
            >全部清除</el-button
          >
        </div>
      </div>
      <el-table
        :data="personData.data"
        v-loading="loading"
        element-loading-text="正在加载数据，请耐心等待"
        :max-height="640"
        :min-height="500"
        border
        fit
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column type="selection" width="40"></el-table-column> -->
        <!-- <el-table-column label="序号" prop="id" width="100px" align="center" /> -->
        <el-table-column label="姓名" align="center">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="开门时间" align="center">
          <template slot-scope="scope">
            {{ scope.row.time }}
          </template>
        </el-table-column>
        <el-table-column label="开门方式" align="center">
          <template slot-scope="scope">
            {{ scope.row.passMethod }}
          </template>
        </el-table-column>
        <el-table-column label="开门结果" align="center">
          <template slot-scope="scope">
            {{ scope.row.passStatus }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          v-if="isAdmin"
          class-name="status-col"
          label="操作"
          width="120"
        >
          <template slot-scope="{ row, $index }">
            <el-row>
              <el-popconfirm
                cancel-button-text="不用了"
                class="m-margin-l10"
                confirm-button-text="好的"
                icon="el-icon-info"
                icon-color="red"
                title="您确定删除当前记录吗？"
                @confirm="doDelLoginRecords"
                @cancel="selectList = []"
              >
                <el-button
                  slot="reference"
                  size="mini"
                  class="light_red_btn"
                  @click="delLoginRecords(row)"
                  >删除
                </el-button>
              </el-popconfirm>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :limit.sync="form.limit"
        :page.sync="form.page"
        :page-sizes="[20, 100, 500]"
        :total="personData.totalCount"
        @pagination="changePage"
      />
    </div>
  </div>
</template>

<script>
  import Cookies from 'js-cookie'
import {
  getOpenDoorRecordsApi,
  delDoorRecordsSingleApi,
  delDoorRecordsAllApi,
  loginRecordsExportUrlApi,
} from "@/api/community/communityPerson";
import { downloadFile } from "@/api/file/file";
import Pagination from "@/components/Pagination";
import FileSaver from "file-saver";
import excelUtil from "@/utils/dealwithExcelUtil.js";
import { cnReg } from "@/utils/validate.js";
import {mapGetters} from "vuex";

export default {
  name: "CommunityPerson",
  components: { Pagination },
  data() {
    return {
      isAdmin:false,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      personData: {data: [], totalCount: 0},
      form: {
        limit: 20,
        page: 1,
        name: "",
        beginTime: "",
        endTime: "",
      },
      loading: true,
      dateTime: [],
      selectList: [],
      passMethodMap: [
        {
          tag: 1,
          label: '平台'
        },
        {
          tag: 2,
          label: '人脸'
        },
        {
          tag: 8,
          label: '通行卡'
        },
        {
          tag: 16,
          label: '密码'
        },
        {
          tag: 128,
          label: '指纹'
        },
      ]
    };
  },
  created() {
    this.isAdmin=Cookies.get('roleId')*1>1?false:true
    this.getOpenDoorRecords();
  },

  methods: {
    cardType(val) {
      let oVal;
      switch (val*1) {
          case 0:
            oVal = '平台';
            break;
          case 1:
            oVal = '人脸';
            break;
          case 2:
            oVal = '掌静脉';
            break;
          case 3:
            oVal = '通行卡';
            break;
          case 4:
            oVal = '密码';
            break;
          case 5:
            oVal = '掌纹';
            break;
          case 6:
            oVal = '虹膜';
            break;
          case 7:
            oVal = '指纹';
            break;
          case 8:
            oVal = '指静脉';
            break;
          default:
            oVal = '';
            break;
        }
      return oVal;
    },
    getOpenDoorRecords() {
      let self = this;
      this.loading = true;
      this.form.beginTime =
        this.dateTime && this.dateTime[0]
          ? this.dateTime[0]
          : "1970-01-01 00:00:00";
      this.form.endTime =
        this.dateTime && this.dateTime[1]
          ? this.dateTime[1]
          : this.$moment(this.$moment().endOf("day").unix() * 1000).format(
              "YYYY-MM-DD HH:mm:ss"
            );
      this.form.beginTime = this.$moment(this.form.beginTime).unix().toString();
      this.form.endTime = this.$moment(this.form.endTime).unix().toString();

      getOpenDoorRecordsApi(this.form).then((res) => {
        if (!res.data) {
          self.loading = false;
          return false;
        }

        res.data.forEach(item => {
          // item.passMethod = self.cardType(item.passMethod);
          let mdStr = ''
          this.passMethodMap.forEach(md => {
            let { tag, label } = md
            if ((item.passMethod & tag) === tag) {
              if (mdStr === '') mdStr = label
              // else mdStr += ` + ${label}`
              else mdStr = '组合'
            }
          })
          item.passMethod = mdStr

          switch (item.passStatus*1) {
            case 0:
              item.passStatus = '成功';
              break;
            case 1:
              item.passStatus = '失败(闸机控制已关闭)';
              break;
            case 2:
              item.passStatus = '失败(违反通行策略)';
              break;
            case 5:
              item.passStatus = '失败(不在有效期)';
              break;
            case 6:
              item.passStatus = '失败(未注册)';
              break;
            case 7:
              item.passStatus = '失败(黑名单)';
              break;
            case 8:
              item.passStatus = '失败(人员personId不相同)';
              break;
            case 9:
              item.passStatus = '组合识别失败';
              break;
            case 99:
              item.passStatus = '组合识别超时';
              break;
          }
          item.time = this.$moment(item.time * 1000).format("YYYY-MM-DD HH:mm:ss");
        });
        self.personData = res;
        console.log(255, self.personData);
        self.loading = false;
      });
    },
    onSearch() {
      this.personData.data = [];
      this.personData.totalCount = 0;
      this.form.page = 1
      this.form.limit = 20
      this.getOpenDoorRecords();
    },
    onReset() {
      this.personData.data = [];
      this.personData.totalCount = 0;
      this.form = {
        limit: 20,
        page: 1,
        beginTime: "",
        endTime: "",
      };
      this.dateTime = [];
      this.getOpenDoorRecords();
    },
    changePage(val) {
      console.log(val);
      this.form.page = val.page;
      this.form.limit = val.limit;
      this.getOpenDoorRecords();
    },
    handleSelectionChange(val) {
      console.log(val);
      this.selectList = val;
    },
    doDelLoginRecords() {
      let params = {
      };
      this.selectList.map((item) => {
        params.id = item.id;
      });
      delDoorRecordsSingleApi(params).then((res) => {
        this.$message.success("删除成功");
        this.getOpenDoorRecords();
      });
    },
    delLoginRecords(row) {
      this.selectList = [row];
    },
    handleDeleteBatch() {
      if (!this.selectList || this.selectList.length === 0) {
        this.$message.warning("请选择删除记录");
        return;
      }
      let params = {
        id: [],
      };
      this.selectList.map((item) => {
        params.id.push(item.id);
      });

      const h = this.$createElement;
      this.$msgbox({
        title: "提示",
        message: h("p", null, [
          h("span", null, `此操作将永久删除所选`),
          h("i", { style: "color: #f00" }, this.selectList.length),
          h("span", null, "个记录, 是否继续?"),
        ]),
        showCancelButton: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        beforeClose: (action, instance, done) => {
          if (action === "confirm") {
            done();
          } else {
            done();
          }
        },
      }).then((action) => {
        delDoorRecordsSingleApi(params).then((res) => {
          this.$message.success("删除成功");
          this.getOpenDoorRecords();
        });
      });

      return false;
      this.$confirm("此操作将永久删除所选记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delDoorRecordsSingleApi(params).then((res) => {
            this.$message.success("删除成功");
            this.getOpenDoorRecords();
          });
        })
        .catch(() => {});
    },
    delDoorRecordsAll() {
      this.$confirm("此操作将永久删除所有记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delDoorRecordsAllApi().then((res) => {
            this.$message.success("删除成功");
            this.personData.data = [];
            this.personData.totalCount = 0;
            this.getOpenDoorRecords();
          });
        })
        .catch(() => {});
    },
    // 导出
    doDownloadFile() {
      let params = {
        beginTime: "",
        endTime: "",
        page: -1,
        limit: -1,
      };
      loginRecordsExportUrlApi(params).then((res) => {
        let downLoadfile = process.env.VUE_APP_BASE_URL + res.url;
        this.download(downLoadfile, new Date().getTime());
      });
    },
    download(href, title) {
      const a = document.createElement("a");
      a.setAttribute("href", href);
      a.setAttribute("download", title);
      a.click();
    },
  },
  computed: {
    ...mapGetters(["roleId"]),
  },
};
</script>

<style lang="scss" scoped>
/deep/ .hide .el-upload--picture-card {
  display: none;
}
.el-form-box {
  /deep/ {
    .numrule input::-webkit-outer-spin-button,
    .numrule input::-webkit-inner-spin-button {
      -webkit-appearance: none !important;
    }
    .numrule input[type="number"] {
      -moz-appearance: textfield;
    }
  }
}
</style>
